# -*- coding: utf-8 -*-
import os
from typing import Optional
import pytest
from utils.logger import log
from config.config import JSON_REPORT, HTML_REPORT


def run(scope: str, test_path: Optional[str] = None, k_expr: Optional[str] = None) -> int:
    """
    统一的用例执行入口：按 scope 组织 pytest 运行参数，并在结束后返回退出码
    """
    log.info("=" * 60 + "begin testing" + "=" * 60)

    options = ["--alluredir=%s" % JSON_REPORT, "--clean-alluredir"]
    if test_path:
        options.insert(0, test_path)

    if scope == 'web':
        if k_expr:
            options[0:0] = ["-k", k_expr]
    elif scope == 'app':
        default_k = "test_management_app"
        k_to_use = k_expr if k_expr else default_k
        options[0:0] = ["-k", k_to_use]
    elif scope == 'c':
        default_k = "test_user_termainal"
        k_to_use = k_expr if k_expr else default_k
        options[0:0] = ["-k", k_to_use]
    elif scope == 'all':
        if k_expr:
            options[0:0] = ["-k", k_expr]
    else:
        log.error("未知的运行范围 scope=%s" % scope)

    exit_code = pytest.main(options)
    return exit_code


def generate_report_and_notify(exit_code: int):
    """生成 Allure 报告并进行通知（如有需要）"""
    os.system("allure generate %s -o %s --clean" % (JSON_REPORT, HTML_REPORT))
    # 如需通知，可在外部自行调用 Feishu 组件


